package requests

import (
	"github.com/gin-gonic/gin"
	"github.com/thedevsaddam/govalidator"

	"github.com/runningwater/gohub/pkg/captcha"
)

type VerifyCodeRequest struct {
	Phone string `json:"phone,omitempty" valid:"phone"`

	CaptchaID     string `json:"captcha_id,omitempty" valid:"captcha_id"`
	CaptchaAnswer string `json:"captcha_answer,omitempty" valid:"captcha_answer"`
}

func VerifyCodePhone(data any, c *gin.Context) map[string][]string {

	// 1. 定制认证规则
	rules := govalidator.MapData{
		"phone":          []string{"required", "digits:11"},
		"captcha_id":     []string{"required"},
		"captcha_answer": []string{"required", "digits:6"},
	}
	// 2. 定制错误信息
	messages := govalidator.MapData{
		"phone": []string{
			"required:手机号不能为空",
			"digits:手机号格式不正确,长度必须为11位",
		},
		"captcha_id": []string{
			"required:验证码ID不能为空",
		},
		"captcha_answer": []string{
			"required:验证码不能为空",
			"digits:验证码格式不正确,长度必须为6位",
		},
	}

	errs := validate(data, rules, messages)

	// Captcha 图片验证
	_data := data.(*VerifyCodeRequest)
	if ok := captcha.NewCaptcha().VerifyCaptcha(_data.CaptchaID, _data.CaptchaAnswer); !ok {
		errs["captcha_answer"] = append(errs["captcha_answer"], "验证码错误")
	}
	// 3. 返回错误信息
	return errs
}

type VerifyCodeEmailRequest struct {
	Email string `json:"email,omitempty" valid:"email"`

	CaptchaID     string `json:"captcha_id,omitempty" valid:"captcha_id"`
	CaptchaAnswer string `json:"captcha_answer,omitempty" valid:"captcha_answer"`
}

func VerifyCodeEmail(data any, c *gin.Context) map[string][]string {
	// 1. 定制认证规则
	rules := govalidator.MapData{
		"email":          []string{"required", "min:4", "max:30", "email"},
		"captcha_id":     []string{"required"},
		"captcha_answer": []string{"required", "digits:6"},
	}
	// 2. 定制错误信息
	messages := govalidator.MapData{
		"email": []string{
			"required:邮箱不能为空",
			"min:邮箱长度需大于 4",
			"max:邮箱长度需小于 30",
			"email:邮箱格式不正确",
		},
		"captcha_id": []string{
			"required:验证码ID不能为空",
		},
		"captcha_answer": []string{
			"required:验证码不能为空",
			"digits:验证码格式不正确,长度必须为6位",
		},
	}

	errs := validate(data, rules, messages)

	// Captcha 图片验证
	_data := data.(*VerifyCodeEmailRequest)
	if ok := captcha.NewCaptcha().VerifyCaptcha(_data.CaptchaID, _data.CaptchaAnswer); !ok {
		errs["captcha_answer"] = append(errs["captcha_answer"], "验证码错误")
	}

	// 3. 返回错误信息
	return errs
}
